import { ArticleDetail, Comment } from '@/types/data'
import { ArticleDetailAction } from '@/types/store'

type State = {
  info: ArticleDetail
  comment: Comment
}

const initState: State = {
  info: {}, // 文章详情
  comment: {}
} as State

export default function articleDetail (
  state = initState,
  action: ArticleDetailAction
) {
  if (action.type === 'articleDetail/setArticleInfo') {
    return { ...state, info: action.payload }
  } else if (action.type === 'article/saveComment') {
    const old = state.comment.results || []
    return {
      ...state,
      comment: {
        ...action.payload,
        results: [...old, ...action.payload.results]
      }
    }
  } else if (action.type === 'article/saveNewComment') {
    const newResults = [action.payload, ...state.comment.results]
    return {
      ...state,
      info: { ...state.info, comm_count: state.info.comm_count + 1 },
      comment: { ...state.comment, results: newResults }
    }
  }
  return state
}
